package esa.android;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;

import android.util.Log;

public class JSONHttpRequest {

	private String url;

	private static final String ENCODING = "UTF-8";

	public JSONHttpRequest(String url) {
		this.url = url;
	}

	public JSONArray doPOSTRequest(Object... params) {

		InputStream is = null;

		try {
			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost(url);

			addParameters(params, httppost);

			HttpResponse response = httpclient.execute(httppost);
			HttpEntity entity = response.getEntity();
			is = entity.getContent();

		} catch (IOException e) {
			Log.e("LunchMenu", "Error in http connection: " + e.toString());
			return null;
		}

		return parseJSON(is);
	}

	protected JSONArray parseJSON(InputStream is) {
		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(is, ENCODING));
			StringBuilder sb = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
			is.close();
			String result = sb.toString();
			Log.i("LunchMenu", "Received json: " + result);

			try {
				JSONArray jArray = new JSONArray(result);
				return jArray;
			} catch (JSONException e) {
				Log.e("LunchMenu", "Error parsing data: " + e.toString());
				return null;
			}

		} catch (IOException e) {
			Log.e("LunchMenu", "Error converting result: " + e.toString());
			return null;
		}
	}

	protected void addParameters(Object[] params, HttpEntityEnclosingRequestBase request) {

		if (params == null || params.length < 2)
			return;

		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
		for (int i = 0; i < params.length; i = i + 2) {
			String name = params[i].toString();
			Object value = params[i + 1];
			if (value instanceof Collection) {
				Collection<?> values = (Collection<?>) value;
				for (Object v : values) {
					nameValuePairs.add(new BasicNameValuePair(name, v.toString()));
				}
			} else {
				nameValuePairs.add(new BasicNameValuePair(name, value.toString()));
			}
		}
		try {
			request.setEntity(new UrlEncodedFormEntity(nameValuePairs));
		} catch (UnsupportedEncodingException e) {
			Log.e("LunchMenu", "Could not add http parameters:" + e.toString());
		}

	}
}
